﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Media;
using System.Globalization;
using TranslatorService.Speech;

namespace TranslatorService.Example
{
    class Program
    {
        private const string CLIENT_ID = "";
        private const string CLIENT_SECRET = "";

        static void Main(string[] args)
        {
            if (string.IsNullOrEmpty(CLIENT_ID) || string.IsNullOrEmpty(CLIENT_SECRET))
            {
                Console.WriteLine("You must obtain a Client ID and Secret in order to use this application. Please visit Azure DataMarket at https://datamarket.azure.com/developer/applications to get one.\r\nThen, go to https://datamarket.azure.com/dataset/1899a118-d202-492c-aa16-ba21c33c06cb and subscribe the Microsoft Translator Service.\n");
                Console.ReadKey();
                return;
            }

            // Create the object that retrieves speech streams.
            SpeechSynthesizer speech = new SpeechSynthesizer(CLIENT_ID, CLIENT_SECRET);
            speech.SpeakCompleted += new EventHandler<SpeechEventArgs>(speech_SpeakCompleted);
            //speech.TranslateCompleted += new EventHandler<TranslateEventArgs>(speech_TranslateCompleted);
            speech.AudioFormat = SpeakStreamFormat.Wave;
            speech.AudioQuality = SpeakStreamQuality.MaxQuality;
            speech.AutoDetectLanguage = true;
            speech.AutomaticTranslation = true;

            Console.WriteLine("Retrieving the list of supported languages...");
            try
            {
                string[] languages = speech.GetLanguages();

                Console.WriteLine("Found {0} supported languges:", languages.Length);
                foreach (var lang in languages)
                {
                    Console.WriteLine("{0} - {1}", lang, CultureInfo.GetCultureInfo(lang).DisplayName);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error during the request: {0}", ex.Message);
            }

            Console.WriteLine("\n");

            bool quit = false;
            while (!quit)
            {
                try
                {
                    Console.Write("Insert the text to be spoken (empty to terminate): ");
                    string text = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(text))
                    {
                        quit = true;
                        continue;
                    }

                    Console.Write("Do you want to directly speak this text using language auto-detection (Y/N)? ");
                    string autoDetect = Console.ReadLine().ToLower();
                    if (autoDetect == "y")
                    {
                        Console.WriteLine("Submitting request... \n");
                        speech.AutoDetectLanguage = true;
                        speech.SpeakAsync(text);
                        continue;
                    }

                    Console.Write("Specify the text language (empty to terminate): ");
                    string language = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(language))
                    {
                        quit = true;
                        continue;
                    }

                    Console.Write("Do you want to Speak the text (S) or just Translate it (T)? ");
                    string action = Console.ReadLine().ToLower();

                    Console.Write("Submitting request... ");
                    
                    if (action == "t")
                    {
                        // Translate the specified text in a synchronous way.
                        var translatedText = speech.Translate(text, language);
                        Console.Write("\nTranslated text: " + translatedText);
                    }
                    else
                    {
                        // Retrieve the stream of wave-file speaking the passed-in text in the desired language. 
                        //using (MemoryStream stream = speech.GetSpeakStream(text, language) as MemoryStream)
                        //{
                        //    File.WriteAllBytes(@"D:\Audio.mp3", stream.ToArray());
                        //    //var length = stream.Length;
                        //    //using (SoundPlayer player = new SoundPlayer(stream))
                        //    //    player.PlaySync();
                        //}

                        // Speak the passed-in text in the desired language, in an asynchronous way.
                        // When this operation completes, the speech_SpeakCompleted event is raised.
                        speech.SpeakAsync(text, language);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error during the request: {0}", ex.Message);
                }

                Console.WriteLine("\n");
            }
        }

        //private static void speech_TranslateCompleted(object sender, TranslateEventArgs e)
        //{
        //    if (e.Error != null)
        //        Console.WriteLine("Erorr: " + e.Error.Message);
        //    else
        //        Console.WriteLine("Translated text: " + e.TranslatedText);
        //}

        private static void speech_SpeakCompleted(object sender, SpeechEventArgs e)
        {
            if (e.Error != null)
                Console.WriteLine("Erorr: " + e.Error.Message);
        }
    }
}
